package com.xc.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.xc.common.ServerResponse;
import com.xc.dao.StockOptionMapper;
import com.xc.pojo.StockOption;
import com.xc.pojo.User;
import com.xc.service.IStockOptionService;
import com.xc.service.IUserService;
import com.xc.utils.stock.sina.SinaStockApi;
import com.xc.vo.stock.StockOptionListVO;
import com.xc.vo.stock.StockVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author mipha
 * @version 1.0
 * @date 2019/2/16 3:01 PM
 */
@Service("iStockOptionService")
@Slf4j
public class StockOptionServiceImpl implements IStockOptionService {

    @Autowired
    StockOptionMapper stockOptionMapper;
    @Autowired
    IUserService iUserService;


    @Override
    public ServerResponse<PageInfo> findMyStockOptions(String keyWords, HttpServletRequest request, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum,pageSize);

        User user = iUserService.getCurrentUser(request);

        List<StockOption> stockOptions = stockOptionMapper.findMyOptionByKeywords(user.getId(),keyWords);
        List<StockOptionListVO> stockOptionListVOS = Lists.newArrayList();
        for (StockOption option : stockOptions){
            StockOptionListVO stockOptionListVO = assembleStockOptionListVO(option);
            stockOptionListVOS.add(stockOptionListVO);
        }

        PageInfo pageInfo = new PageInfo(stockOptions);
        pageInfo.setList(stockOptionListVOS);

        return ServerResponse.createBySuccess(pageInfo);
    }

    @Override
    public ServerResponse isOption(Integer uid, String code) {

        StockOption stockOption = stockOptionMapper.isOption(uid,code);
        if(stockOption == null){
            return ServerResponse.createBySuccessMsg("未添加");
        }else{
            return ServerResponse.createByErrorMsg("已添加");
        }
    }

    private StockOptionListVO assembleStockOptionListVO(StockOption option){
        StockOptionListVO stockOptionListVO = new StockOptionListVO();

        stockOptionListVO.setId(option.getId());
        stockOptionListVO.setStockName(option.getStockName());
        stockOptionListVO.setStockCode(option.getStockCode());
        stockOptionListVO.setStockGid(option.getStockGid());

        StockVO stockVO = SinaStockApi.assembleStockVO(SinaStockApi
                .getSinaStock(option.getStockGid()));

        //  设置行情
        stockOptionListVO.setNowPrice(stockVO.getNowPrice());
        stockOptionListVO.setHcrate(stockVO.getHcrate().toString());
        stockOptionListVO.setPreclose_px(stockVO.getPreclose_px());
        stockOptionListVO.setOpen_px(stockVO.getOpen_px());

        return stockOptionListVO;
    }




}
